package com.nuanshui.heatedloan.controller.display.wallet;


import com.alibaba.dubbo.config.annotation.Reference;
import com.nuanshui.heatedloan.service.services.CommonTool;
import com.nuanshui.framework.exception.BizException;
import com.nuanshui.framework.exception.GlobalErrorCode;
import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.framework.security.AESUtil;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.heatedloan.msgcenter.facade.VerificationFacade;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.controller.BaseController;
import com.nuanshui.heatedloan.controller.ResponseObject;
import com.nuanshui.heatedloan.dal.IdTypeHandler;
import com.nuanshui.heatedloan.fund.facade.PayPasswordService;
import com.nuanshui.heatedloan.msgcenter.model.AliSmsSecurityCodeTemplateEnum;
import com.nuanshui.heatedloan.userinfo.facade.UserQueryService;
import com.nuanshui.heatedloan.userinfo.facade.UserService;
import com.nuanshui.heatedloan.userinfo.facade.UserStateService;
import com.nuanshui.heatedloan.userinfo.model.User;
import com.nuanshui.heatedloan.userinfo.tool.UserTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/user/payPassword/")
public class PayPasswordController extends BaseController{


	private static final Logger  logger = LoggerFactory.getLogger("payPassword");
	
	@Reference(url=GlobalParam.FUND_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.FUND_DUBBO_SERVER_VERSION)
	private PayPasswordService payPasswordService;
	
	@Reference(url=GlobalParam.USER_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
	private UserService userService;

	@Reference(url=GlobalParam.USER_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
	private UserQueryService userQueryService;

	@Reference(url=GlobalParam.USER_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
	private UserStateService userStateService;

	@Reference(url=GlobalParam.USER_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
	private UserTool userTool;
	
	@Autowired
	private CommonTool commonTool;

	@Reference(url = GlobalParam.MSGCENTER_DUBBO_SERVER, timeout = GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.MSGCENTER_DUBBO_SERVER_VERSION )
	private VerificationFacade veriFacade;
	
	
	/**
	 * 获取加密的公钥
	 * @param 
	 * @author guohao
	 * @date 2016年3月14日 下午6:48:42
	 */
	@RequestMapping(value = "loadPublishKey",method = RequestMethod.POST)
	public String loadPublishKey() {
		LogUtil.info(logger, "获取加密的公钥");
		return success(commonTool.getDefaultPublishKey(getSafeToken()));	
	}
	
	@RequestMapping(value = "bindPhoneStatus",method = RequestMethod.POST)
	public String bindPhoneStatus() {
		//检查是否绑定手机号
		String userId = IdTypeHandler.encode(1);
		Map<String, Boolean> map = new HashMap<String, Boolean>();
		boolean isBindPhone = userStateService.bindPhoneStatus(userId);
		map.put("isBindPhone", isBindPhone);
		LogUtil.info(logger, "获得绑定手机状态:"+ (isBindPhone ? "已绑定":"未绑定"));
		return success(map);
	}
	
	/**
	 * 检查用户是否设置支付密码
	 * @param 
	 * @author zhangqing
	 * @date 2016年3月1日 上午11:45:02
	 * @since 2.5.0
	 */
	@RequestMapping(value = "checkSetPayPassword",method = RequestMethod.POST)
	public String checkSetPayPassword() {
		String userId =  IdTypeHandler.encode(1);
		Map<String, Boolean> map = new HashMap<String, Boolean>();
		boolean isSetPayPassword = payPasswordService.isSetPayPassword(userId);
		map.put("isSetPayPassword", isSetPayPassword);
		LogUtil.info(logger, "此用户"+(isSetPayPassword ? "已":"未") + "设置密码");
		return success(map);
	}
	
	/**
	 * 获取用户绑定的手机
	 * @param 
	 * @author zhangqing
	 * @date 2016年3月2日 下午2:46:43
	 */
	@RequestMapping(value = "getUserPhone",method = RequestMethod.POST)
	public String getUserPhone() {
		String userId =getCurrentUser().getId();
		User user = userQueryService.load(userId);
		//检查是否绑定手机号
		Map<String, Object> map = new HashMap<String, Object>();
		boolean isBindPhone = userStateService.bindPhoneStatus(userId);
		if (isBindPhone) {
			map.put("userPhone", user.getPhone());
		}
		map.put("isBindPhone", isBindPhone);
		LogUtil.info(logger, "此用户"+(isBindPhone ? "已":"未") + "绑定手机");
		return success(map);
	}
	
	/**
	 * 这个好像不用了。。
	 *
	 *
	 * 绑定手机号后设置支付密码，不需要再次发送短信验证码
	 * @param password 支付密码
	 * @author zhangqing
	 * @date 2016年3月2日 下午4:08:12
	 * @since 2.5.0

	@RequestMapping("setPayPwd")
	public String setPayPwd(String password) {

		if (SysStringUtils.isEmpty(password)) {
			return error("请输入支付密码。");
		}

		if(commonTool.allowIOSExecute("110")){
			password = new String(AESUtil.decrypt(AESUtil.sixteenStrToByte(password)));
			LogUtil.info(logger, "使用新版本的解密方式解密");
		}else{
			password = commonTool.decryptPassword(getSafeToken(), password);
		}

		//设置支付密码
		payPasswordService.setPayPassword(password, getCurrentUser().getId());
		return success(Boolean.TRUE);
	}*/
	
	/**
	 * 设置支付密码1，发送短信验证码
	 * @param 
	 * @author zhangqing
	 * @date 2016年3月2日 上午10:19:25
	 * @since 2.5.0
	 */
	@RequestMapping(value = "set-payPwd-sms",method = RequestMethod.POST)
	public ResponseObject<Boolean> sendPayPwdCode(Integer length) {
		LogUtil.info(logger, "根据用户绑定的手机号码,设定支付密码");
		//获取用户绑定的手机号
		User user = userQueryService.load(getCurrentUser().getId());
		veriFacade.generateCode(user.getPhone(), AliSmsSecurityCodeTemplateEnum.SET_PAY_PASSWD, length);
		return new ResponseObject<Boolean>(Boolean.TRUE);
	}
	
	/**
	 * 设置支付密码2,，验证smsCode，并设置支付密码
	 * @param 
	 * @author zhangqing
	 * @throws Exception 
	 * @date 2016年3月1日 上午11:46:12
	 * @since 2.5.0
	 */
	@RequestMapping(value = "setPayPassword",method = RequestMethod.POST)
	public String setPayPassword(String password,String smscode) throws Exception {
		String currentUserId  = getCurrentUser().getId();
		LogUtil.info(logger, "通过验证smscode:"+smscode+"设置支付密码");
		if (SysStringUtils.isEmpty(password)) {
			return error("请输入支付密码。");
		}
		if(commonTool.allowIOSExecute("110")){
			LogUtil.info(logger, "使用新版本的解密方式，解密前------"+password);
			password = new String(AESUtil.decrypt(AESUtil.sixteenStrToByte(password)));
			LogUtil.info(logger, "使用新版本的解密方式，解密后------"+password);
		}else{
			password = commonTool.decryptPassword(getSafeToken(), password);
			password = password.substring(0,6);
			password = SysStringUtils.reverse(password);
		}

		User user = userQueryService.load(getCurrentUser().getId());
		// 验证短信验证码
		Boolean valid = veriFacade.verifyCode(user.getPhone(),
				smscode, AliSmsSecurityCodeTemplateEnum.SET_PAY_PASSWD);
		if (!valid) {
			throw new BizException(GlobalErrorCode.UNKNOWN,"验证码错误");
			//throw new BizException(GlobalErrorCode.UNKNOWN,("registerExecute.smscode.not.valid"));
		}
		boolean isSetPayPassword = payPasswordService.isSetPayPassword(currentUserId);
		if (isSetPayPassword)  {//已经设置支付密码，则修改支付密码
			payPasswordService.changePayPassword(password, currentUserId);
		} else { //未设置过支付密码
			//设置支付密码
			payPasswordService.setPayPassword(password, currentUserId);
		}
		return success(Boolean.TRUE);
	}
	
	/**
	 * 修改支付密码
	 * @param  oldPwd 旧支付密码 newPwd 新支付密码
	 * @author zhangqing
	 * @date 2016年3月1日 下午2:55:05
	 * @since 2.5.0
	 */
	@RequestMapping(value = "changePayPassword",method = RequestMethod.POST)
	public String changePayPassword(String oldPwd,String newPwd){
		LogUtil.info(logger, "修改支付密码:旧密码:"+oldPwd + ",新密码:" + newPwd);
		Map<String, Boolean> map = new HashMap<String, Boolean>();
		boolean isPass = payPasswordService.verifyPayPassword(oldPwd, userTool.getCurrentUserNotCheck().getId());
		if (isPass) {
			payPasswordService.changePayPassword(newPwd, userTool.getCurrentUserNotCheck().getId());
		}
		map.put("isPass", isPass);
		return success(map);
	}
}

